<template>
    <el-card shadow="never" class="border-0">
      <!-- 搜索 -->
      <el-form :model="searchForm" label-width="90px" class="mb-3" size="small">
        <el-row :gutter="20">
          <el-col :span="5" :offset="0">
            <el-form-item label="产品类型名称">
              <el-input v-model="searchForm.deviceTypeName" placeholder="产品类型名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <div class="flex items-center justify-end">
              <el-button type="primary" @click="initTableData(1)">搜索</el-button>
              <el-button @click="resetSearchForm">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
  
      <!-- 新增|刷新 -->
      <div class="flex items-center justify-between mb-4">
        <el-button type="primary" size="small" @click="handleCreate">新增</el-button>
        <el-tooltip effect="dark" content="刷新数据" placement="top">
          <el-button text @click="initTableData">
            <el-icon :size="20">
              <Refresh />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
  
      <!-- 表格数据 -->
      <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">

        <el-table-column label="产品类型名称" align="center">
          <template #default="{ row }">
            {{ row.deviceTypeName }}
          </template>
        </el-table-column>

        <el-table-column label="产品型号" align="center">
          <template #default="{ row }">
            {{ row.deviceTypeCode }}
          </template>
        </el-table-column>

        <el-table-column label="产品分类" align="center">
          <template #default="{ row }">
            {{ row.deviceClassify }}
          </template>
        </el-table-column>
  
        <el-table-column label="备注" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.remarks }}
          </template>
        </el-table-column>

        <el-table-column label="操作手册" align="center">
          <template #default="{ row }">
            {{ row.infoLibraryTitle }}
          </template>
        </el-table-column>
  
        <el-table-column label="创建时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="更新时间" align="center">
          <template #default="{ row }">
            {{ dateFormatter(row.updateTime) }}
          </template>
        </el-table-column>
  
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
            <div v-else>
  
              <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>
  
              <el-popconfirm title="是否要删除该产品类型？" confirmButtonText="确认" cancelButtonText="取消"
                @confirm="handleDelete(scope.row.deviceTypeId)">
                <template #reference>
                  <el-button text type="primary" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页组件 -->
      <div class="flex items-center justify-center mt-5">
        <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage" :page-size="limit"
          @current-change="initTableData" />
      </div>
  
      <!-- 新增|修改弹窗 -->
      <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
  
        <el-form :model="form" ref="formRef" :rules="rules" label-width="120px" :inline="false">
          
          <el-form-item label="产品类型名称" prop="deviceTypeName">
            <el-input v-model="form.deviceTypeName" placeholder="产品类型名称"></el-input>
          </el-form-item>

          <el-form-item label="产品型号" prop="deviceTypeCode">
            <el-input v-model="form.deviceTypeCode" placeholder="产品型号"></el-input>
          </el-form-item>

          <el-form-item label="产品分类" prop="deviceClassify">
            <el-input v-model="form.deviceClassify" placeholder="产品分类"></el-input>
          </el-form-item>
  
          <el-form-item label="备注">
            <el-input type="textarea" v-model="form.remarks" placeholder="备注"></el-input>
          </el-form-item>

          <el-form-item label="操作手册" prop="infoLibraryId">
              <el-button plain @click="dialogTableVisible_infoLibrary = true">
                  {{ checkedInfoLibrary == null ? '选择操作手册' : checkedInfoLibrary.title }}
              </el-button>
              <el-button v-if="null != checkedInfoLibrary && null != checkedInfoLibrary.title" type="primary" size="small" text @click="cleanFile()">移除</el-button>
          </el-form-item>
  
        </el-form>
      </FormDrawer>
    </el-card>

    <!-- 选择操作手册弹窗 -->
    <el-dialog v-model="dialogTableVisible_infoLibrary" title="选择操作手册" width="70%" align-center>
      <SelectInfoLibrary v-if="dialogTableVisible_infoLibrary" @getCheckedInfoLibrary="getCheckedInfoLibrary" />
      <template #footer>
          <div class="dialog-footer">
              <el-button type="primary" @click="dialogTableVisible_infoLibrary = false">
                  确认
              </el-button>
          </div>
      </template>
    </el-dialog>
  </template>

  <script setup>
  import { ref, reactive, computed, onMounted } from "vue"
  import FormDrawer from "~/components/FormDrawer.vue";
  import {toast} from "~/composables/util"
  import { dateFormatter } from '~/utils/common.js'
  import SelectInfoLibrary from "~/components/select-info-library.vue";
  import { addDeviceType, updateDeviceType, deleteDeviceType,getDeviceTypeList } from "~/api/supply"

  //选择操作手册弹窗
  const dialogTableVisible_infoLibrary = ref(false)
  const checkedInfoLibrary = ref(null)
  
  // 分页
  const currentPage = ref(1)
  const total = ref(0)
  const limit = ref(10)
  
  // 查询条件
  const searchForm = reactive({
    deviceTypeName: "",
    page: currentPage.value,
    size: limit.value,
  })
  // 重置搜索框
  const resetSearchForm = () => {
    searchForm.deviceTypeName = ""
    initTableData(1)
  }
  
  const tableData = ref([])
  const loading = ref(false)
  
  // 生命周期函数
  onMounted(() => {
    //初始化列表数据
    initTableData()
  })
  
  // 获取数据
  function initTableData(p = null) {
    //指定页码是否为空
    if (typeof p == "number") {
      currentPage.value = p
    }
  
    loading.value = true
    searchForm.page = currentPage.value

    getDeviceTypeList(searchForm)
      .then(res => {
          if(res){
            tableData.value = res.records      
            total.value = res.total
          }else{
            tableData.value = []  
            total.value = 0
          }
      })
      .finally(() => {
        loading.value = false
      })
  }
  
  // 移除文件
  const cleanFile = () => {
    form.infoLibraryId = null
    form.infoLibraryTitle = null
    checkedInfoLibrary.value = null
  }

  // 删除
  const handleDelete = (id) => {
    loading.value = true
    deleteDeviceType(id).then(res => {
        toast("删除成功")
        initTableData()
    })
      .finally(() => {
        loading.value = false
      })
  }
  
  // 表单部分
  const formDrawerRef = ref(null)
  const formRef = ref(null)
  const form = reactive({
    deviceTypeName: null,
    deviceClassify: null,
    deviceTypeCode: null,
    remarks:null,
    //操作手册id，可为空
    infoLibraryId: null,
    //操作手册title，可为空
    infoLibraryTitle: null
  })
  //执行表单校验
  const rules = {
    deviceTypeName: [
      { required: true, message: '产品类型名称不能为空', trigger: 'change' }
    ],
    deviceTypeCode: [
      { required: true, message: '产品型号不能为空', trigger: 'change' }
    ],
    deviceClassify: [
      { required: true, message: '产品分类不能为空', trigger: 'change' }
    ],
    remarks: [
      { required: true, message: '备注信息不能为空', trigger: 'change' }
    ],
  }
  
  //是否是编辑弹窗
  const editId = ref(0)
  const drawerTitle = computed(() => editId.value ? "修改" : "新增")
  
  //提交表单
  const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
      if (!valid) return
  
      //loading
      formDrawerRef.value.showLoading()
  
      //根据是否是修改标记，判断执行新增接口还是修改接口
      const fun = editId.value ? updateDeviceType(editId.value, form) : addDeviceType(form)
  
      fun.then(res => {
        toast(drawerTitle.value + "成功")
        // 修改刷新当前页，新增刷新第一页
        initTableData(editId.value ? false : 1)
        formDrawerRef.value.close()
      })
      .finally(() => {
        //close loading
        formDrawerRef.value.hideLoading()
      })
    })
  }
  
  // 重置表单
  function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
      for (const key in form) {
        form[key] = row[key]
      }
    }
  }
  
  // 新增按钮点击事件
  const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    //将操作手册信息清空
    checkedInfoLibrary.value = null
    resetForm({
      deviceTypeName: null,
      deviceClassify: null,
      deviceTypeCode: null,
      remarks:null,
      //操作手册id，可为空
      infoLibraryId: null,
      //操作手册title，可为空
      infoLibraryTitle: null
    })
    //打开弹窗
    formDrawerRef.value.open()
  }
  
  // 编辑
  const handleEdit = (row) => {
    editId.value = row.deviceTypeId
    //给操作手册信息赋值回显
    if(null != row.infoLibraryId && null != row.infoLibraryTitle){
      checkedInfoLibrary.value = {id: row.infoLibraryId, title: row.infoLibraryTitle}
    }else{
      //将操作手册信息清空
      checkedInfoLibrary.value = null
    }
    resetForm(row)
    formDrawerRef.value.open()
  }

  //获取选择的公司
  function getCheckedInfoLibrary(data) {
      //console.log('checked info library: ', data)
      if (data != null) {
        form.infoLibraryId = data.id
        form.infoLibraryTitle = data.title
        checkedInfoLibrary.value = data
      }
  }

  </script>